package com.ruoyi.common.qy.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class PythonCaller {

    public static boolean checkPythonScriptExists() {
        File scriptFile = new File(pythonScriptPath);
        if (scriptFile.exists()) {
            System.out.println("Python脚本存在: " + scriptFile.getAbsolutePath());
            return true;
        } else {
            System.out.println("Python脚本不存在: " + scriptFile.getAbsolutePath());
            return false;
        }
    }
    static final String pythonScriptPath = "/mnts/jar_work/LiTui/qywechat/xiaohongshu_video.py";
//    static final String pythonScriptPath = "D:\\idea_work_temp\\20241219zhicheng\\spy\\python\\xiaohongshu\\index_java.py";
    public static String getXiaoHongShuVideoUrl(String url) {
        try {
            // 先检查脚本是否存在
            if (!checkPythonScriptExists()) {
                return "错误: 小红书Python脚本不存在";
            }

            // 构建命令
            String[] command = {"python3", pythonScriptPath, url};

            // 执行Python脚本
            Process process = Runtime.getRuntime().exec(command);

            // 读取输出
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));

//            String tempVideoUrl;
            String videoUrl= reader.readLine();

            // 读取标准输出
//            while ((tempVideoUrl = reader.readLine()) != null) {
//                System.out.println("Python输出: " + tempVideoUrl);
//                if(tempVideoUrl.lastIndexOf(".mp4") != -1){
//                    videoUrl = tempVideoUrl;
//                    break;
//                }
//            }
            // 等待进程结束
            process.waitFor();

            return videoUrl != null ? videoUrl : "";

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

//    public static void main(String[] args) {
//        String targetUrl = "https://www.xiaohongshu.com/explore/68f59d18000000000401724c?xsec_token=ABZC-xDAP3W62-LleyCCN8y6IvGNNp758pB8h7-ts0j-k=&xsec_source=pc_feed";
//        String videoUrl = getXiaoHongShuVideoUrl(targetUrl);
//
//        if (!videoUrl.isEmpty()) {
//            System.out.println("获取到的视频URL: " + videoUrl);
//        } else {
//            System.out.println("未找到视频URL");
//        }
//    }
}
